package com.ztk.threadbasic.completableFuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.BiConsumer;
import java.util.function.Function;

public class CompletableFuture02 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> {
            try {
                System.out.println("开始执行有返回结果的supplyAsync方法");
                Thread.sleep(2000);
                System.out.println("开始计算");
                int count = 1;
                for (int i = 0; i < 10; i++) {
                    count *= (count + i);
                }
                return count / 0;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return null;
        });

        future.exceptionally(new Function<Throwable, Integer>() {
            @Override
            public Integer apply(Throwable throwable) {
                System.out.println("程序执行异常，异常原因：" + throwable.getMessage());
                return 0;
            }
        }).join();

        // future.whenComplete(new BiConsumer<Integer, Throwable>() {
        //     @Override
        //     public void accept(Integer integer, Throwable throwable) {
        //         System.out.println("执行完成，返回结果为：" + integer);
        //     }
        // });

    }
}
